package com.tedu.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Author：毕龙
 * Date: 2023/7/21 14:46
 * 获取链接的工具类
 */
public class JDBCUtil {
    //这个类是一个键值对形式的类
    private static Properties properties = new Properties();

    //读取配置文件的数据
    static {
        //获取流对象
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            //将流文件中的数据加载到prop属性
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取链接的方法
    public static Connection getConnection(){
        //加载驱动
        Connection conn = null;
        try {
            String driver = properties.getProperty("driver");
            Class.forName(driver);
            //获取链接
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            conn = DriverManager.getConnection(url, username, password);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //释放资源
    public static void release(ResultSet rs, Statement pstm,Connection conn){

        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (pstm!= null){
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!= null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
